<?php
/**
 * Created by PhpStorm.
 * User: FoxxxZhu
 * Date: 2019/1/15
 * Time: 10:42
 */

namespace Forxx\Api;


use Lavender\Core;
use Lavender\Exception;

class OpenCall extends InnerCall{

    /**
     * 获取签名的url
     * @param $path
     * @param $data
     */
    public function getSignUrl($path,$data,$token){
        if(substr($path,0,4) == "http"){
            return $path;
        }
        $module = "api";
        $ret = preg_match("/^{{(.+)}}/",$path,$match);
        if(isset($match[1])){
            $module = $match[1];
        }
        $baseUrl = $this->getBaseApiHost($module);
        if(empty($baseUrl)){
            throw new  Exception("inner api host key '{$module}' not set!");
        }
        $realPath =  str_replace("{{".$module."}}","",$path);
        $postStr = json_encode($data);
        $appId = isset($_GET['app_id']) ? $_GET['app_id'] :"201901011001";
        $ver = isset($_GET['ver']) ? $_GET['ver'] :"20190101";
        $param = "_input={$postStr}&app_id={$appId}&ver={$ver}";
        $sign = md5(md5($param) . md5($token));
        return $baseUrl.$realPath."?app_id={$appId}&ver={$ver}&sign={$sign}";
    }

    public function getLoginKey($key){
        $val = $this->controller->get_cookie($key);
        return $val;
    }

    public function post($path, array $postData, $timeout = 30)
    {
        $skey = Core::get_config("const",'session_key');
        $sval = $this->getLoginKey($skey);
        $token = time();
        $url = $this->getSignUrl($path,$postData,$token);
        $ip = $this->controller->get_client_ip();
        $header = [
            'X-Forwarded-For:'.$ip,
            'HTTP_CLIENT_IP:'.$ip,
            'X-Real-Ip:'.$ip,
            'APP_ID:'.L_APP_NAME,
            'Cookie:'."{$skey}={$sval};_token={$token}",
        ];
        return Utils::httpJsonp($url,$postData,$timeout,$header);
    }

    public function ajaxPost($path,array $postData){
        $skey = Core::get_config("const",'session_key');
        $sval = $this->getLoginKey($skey);
        $token = time();
        $url = $this->getSignUrl($path,$postData,$token);
        $ip = $this->controller->get_client_ip();
        $header = [
            'X-Forwarded-For:'.$ip,
            'HTTP_CLIENT_IP:'.$ip,
            'X-Real-Ip:'.$ip,
            'APP_ID:'.L_APP_NAME,
            'Cookie:'."{$skey}={$sval};_token={$token}",
        ];
        Core::log("api_call_error",date("Y-m-d H:i:s")."\n post url:\t {$url} \n data: \n ".json_encode($postData,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT)." \n\n");
        Utils::ajaxHttp($url,json_encode($postData,JSON_UNESCAPED_UNICODE),100,$header);
    }

}